class File():
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
    
    def __enter__(self):
        print("entering")
        self.f = open(self.filename, self.mode)
        return self.f
    
    def __exit__(self):
        print("exit")
        self.f.close()

# 使用自定义的上下文管理
with File("a.txt", "w") as f:
    f.write("hello world!")
    pass